package com.lazy.lib.util;

import java.io.UnsupportedEncodingException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class StrUtil {
    protected static Logger logger = LoggerFactory.getLogger("StrUtil");
    
    /**
     * 将字符串转成数字， 对于"0x32"转成0x32, 否则按照十进制处理
     * @param str
     * @return -1 fail
     */
    public static int toInteger(String str) {
        int id  = -1;
        try {
            int radius = 10;
            if (str.startsWith("0x") || str.startsWith("0X")) {
                str = str.substring(2);
                radius = 16;
            }
            id = Integer.valueOf(str, radius);
        } catch (Exception e) {
            logger.error("error when convert string to int " + e.getMessage());
        }
        
        return id;
    }
    
    /**
     * 将字符串转成 double
     * @param str
     * @return
     */
    public static double toDouble(String str) {
        Double ret = 0.0;
        try {
            ret = Double.valueOf(str);
        } catch (Exception e) {
            logger.error("error when convert string to int " + e.getMessage());
        }
        
        return ret;
    }
    /**
     * 返回字符串
     * @param src
     * @return 没有null返回，全部转成“”
     */
    public static String fromAsciiBytes(byte[] src) {
        try {
            return new String(src, "US-ASCII").trim();
        } catch (Exception e) {
            return "";
        }
    }
    
    /**
     * 返回字符串
     * @param src
     * @param index
     * @param len
     * @return 没有null返回，全部转成“”
     */
    public static String fromAsciiBytes(byte[] src, int index, int len) {
        try {
            return new String(src,index,len, "US-ASCII");
        } catch (Exception e) {
            return "";
        }
    }
    
    /**
     * 返回ascii字节数组
     * @param src
     * @return
     */
    public static byte[] toAsciiBytes(String src) {
        try{
            return src.getBytes("US-ASCII");
        }catch(UnsupportedEncodingException e){
            return null;
        }
    }

    public static boolean isStrNullOrBlank(String s) {
        return s == null || s.equals("");
    }
    
    /**
     * @param args
     *
     * @author grind
     * @date Mar 26, 2014 6:25:11 PM
     */
    public static void main(String[] args){
        logger.info("{}", toInteger("32"));
        logger.info("{}", toInteger("0x32"));
    }

}
